package com.anjufang.controller.system;

import java.util.List;
import java.util.Map;

import com.anjufang.common.exception.PHException;
import com.anjufang.controller.BaseController;
import com.anjufang.entity.AdminUser;
import com.anjufang.service.system.AdminUserService;
import com.anjufang.utils.Result;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.TokenManager;
import com.anjufang.utils.constant.Constant;
import com.anjufang.utils.page.PageUtils;
import com.anjufang.utils.page.Query;
import com.anjufang.utils.validator.Assert;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/sys/user/")
public class AdminUserController extends BaseController {

	@Autowired
	private AdminUserService userService;

	/**
	 * 所有用户列表
	 */
	@RequestMapping(value = LIST)
	public PageUtils list(@RequestParam Map<String, Object> params) {

		// 只有超级管理员，才能查看所有管理员列表
		if (TokenManager.getUserId() != Constant.SUPER_ADMIN) {
			params.put("createUserId", TokenManager.getUserId());
		}
		// 查询列表数据
		Query query = new Query(params);
		List<AdminUser> userList = userService.queryList(query);
		int total = userService.queryTotal(query);
		PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

		return pageUtil;
	}

	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("info")
	public Result info() {

		AdminUser user = userService.getAdminUser(TokenManager.getToken().getId());
		return Result.ok().put("user", user);
	}

	/**
	 * 修改个人信息
	 * 
	 * @return
	 */
	@RequestMapping("updateInfo")
	public Result updateInfo(String email, String mobile) {

		AdminUser user = new AdminUser();
		user.setId(TokenManager.getToken().getId());
		user.setEmail(email);
		user.setMobile(mobile);
		user.updateById();
		return Result.ok();
	}

	/**
	 * 修改登录用户密码
	 */
	@RequestMapping("password")
	public Result password(String password, String newPassword) {

		Assert.isBlank(newPassword, "新密码不为能空");

		// sha256加密
		password = new Sha256Hash(password, TokenManager.getToken().getSalt()).toHex();
		// sha256加密
		newPassword = new Sha256Hash(newPassword, TokenManager.getToken().getSalt()).toHex();
		// 更新密码
		AdminUser user = new AdminUser();
		user.setId(TokenManager.getUserId());
		user = user.selectById();
		if (!password.equals(user.getPassword())) {
			return Result.error("原密码不正确");
		}
		user.setPassword(newPassword);
		user.updateById();

		return Result.ok().put("password", newPassword);
	}

	/**
	 * 用户信息
	 */
	@RequestMapping("info/{userId}")
	public Result info(@PathVariable("userId") Long userId) {

		AdminUser user = userService.info(userId);
		return Result.ok().put("user", user);
	}

	/**
	 * 保存用户
	 */
	@RequestMapping(value = SAVE)
	@RequiresPermissions("system/user/save.htm")
	public Result save(@RequestBody AdminUser user) {

		if ("admin".equals(user.getUserName())) {
			throw new PHException("新增用户名不能'admin'!");
		}
		int count = userService.selectCountByUserName(user);
		if (count > 0) {
			throw new PHException("不能添加同名<" + user.getUserName() + ">用户!");
		}
		verifyForm(user);
		if (StringUtils.isBlank(user.getPassword())) {
			return Result.error("请输入密码!");
		}
		user.setCreateUserId(TokenManager.getUserId());
		userService.save(user);

		return Result.ok();
	}

	/**
	 * 修改用户
	 */
	@RequestMapping(value = UPDATE)
	@RequiresPermissions("system/user/update.htm")
	public Result update(@RequestBody AdminUser user) {

		verifyForm(user);
		AdminUser old = new AdminUser().selectById(user.getId());
		if (old.getPassword().equals(user.getPassword())) {
			user.setPassword(null);
		}
		user.setCreateUserId(TokenManager.getUserId());
		userService.update(user);

		return Result.ok();
	}

	/**
	 * 删除用户
	 */
	@RequestMapping(value = DELETE)
	@RequiresPermissions("system/user/delete.htm")
	public Result delete(Long id) {

		if (id == 1L) {
			return Result.error("系统管理员不能删除");
		}
		if (id.equals(TokenManager.getUserId())) {
			return Result.error("当前用户不能删除");
		}
		new AdminUser().deleteById(id);
		return Result.ok();
	}

	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(AdminUser user) {

		if (StringUtils.isBlank(user.getUserName())) {
			throw new PHException("用户名不能为空");
		}
		if (StringUtils.isBlank(user.getEmail())) {
			throw new PHException("邮箱不能为空");
		}
		if (StringUtils.isBlank(user.getMobile())) {
			throw new PHException("手机号不能为空");
		}
	}

}
